package com.mida.bms.report.service.impl;

import com.mida.bms.report.common.cons.CharacterConst;
import com.mida.bms.report.entity.DocStructReport;
import com.mida.bms.report.entity.DocStructReportLifeCycle;
import com.mida.bms.report.entity.DocStructReportPdf;
import com.mida.bms.report.mapper.*;
import com.mida.bms.report.service.DocReportPdfService;
import com.mida.bms.report.service.DocStructTemplateInfoService;
import com.mida.bms.report.service.SoidService;
import com.mida.bms.report.service.SrvDocReportService;
import com.mida.bms.report.util.FTPUtil;
import com.mida.bms.report.vo.DocReportRequisitionRelationVo;
import com.mida.bms.report.vo.ReportSearchRequest;
import com.mida.tool.common.result.ActionResult;
import com.mida.tool.common.result.ListResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.StopWatch;
import org.apache.commons.net.ftp.FTPClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.*;

import static com.mida.tool.common.result.BaseResult.*;

@Service
@Transactional
@Slf4j
@DependsOn("loadFromDatabasePropertyConfig")
public class DocReportPdfServiceImpl implements DocReportPdfService {


    // ID生成器
    @Autowired
    private SoidService soidService;

    // 报告生命周期
    @Autowired
    private DocStructReportLifeCycleMapper docStructReportLifeCycleMapper;

    // 结构化报告和检查实例的关系
    @Autowired
    private DocReportRequisitionRelationMapper docReportRequisitionRelationMapper;

    // 结构化报告PDF存储
    @Autowired
    private DocStructReportPdfMapper docStructReportPdfMapper;

    @Autowired
    private DocStructReportMapper docStructReportMapper;

    @Autowired
    private SrvDocReportService srvDocReportService;

    // FTP
    @Value("${nginx.pdf.url}")
    private String nginxUrl;

    @Value("${ftp.imgPath}")
    private String imgPath;

    @Value("${ftp.server.host}")
    private String ftpHost;

    @Value("${ftp.server.port}")
    private int ftpPort;

    @Value("${ftp.server.username}")
    private String ftpUserName;

    @Value("${ftp.server.password}")
    private String ftpPassword;

//    @Override
//    public ActionResult savePdf(Long stReportSoid, MultipartFile file, Long employeeSoid) {
//        log.info("开始保存报告pdf");
//        StopWatch stopWatch = StopWatch.createStarted();
//        ActionResult actionResult = new ActionResult();
//
//        FTPUtil ftpUtil = new FTPUtil();
//        // 获取FTPClient对象
//        FTPClient ftpClient = ftpUtil.getFTPClient(ftpHost, ftpPort, ftpUserName, ftpPassword);
//
//        try {
//            if (ObjectUtils.isEmpty(employeeSoid)) {
//                buildBadRequestActionWarn(actionResult, "获取不到用户信息");
//                return actionResult;
//            }
//
//            if (ObjectUtils.isEmpty(stReportSoid)) {
//                buildBadRequestActionWarn(actionResult, "报告存储信息标识");
//                return actionResult;
//            }
//
//            if (file.isEmpty()) {
//                buildBadRequestActionWarn(actionResult, "pdf文件不能为空");
//                return actionResult;
//            }
//
//            // 上传pdf文件
//            String savePath = ftpUtil.uploadFile(ftpClient, file, imgPath);
//            StringBuffer stringBuffer = new StringBuffer(nginxUrl);
//            StringBuffer url = stringBuffer.append("/").append(imgPath).append("/").append(savePath);
//
//            if (ObjectUtils.isNotEmpty(stReportSoid)) {
//
//                // 查询最新操作的一条生命周期记录
//                DocStructReportLifeCycle docStructReportLifeCycle = docStructReportLifeCycleMapper.selectNewestByStReportSoid(stReportSoid);
//                if (ObjectUtils.isNotEmpty(docStructReportLifeCycle)) {
//                    DocStructReportPdf docStructReportPdf = docStructReportPdfMapper.selectByLifeCycleSoid(docStructReportLifeCycle.getStReportLifeCycleSoid());
//                    if (docStructReportPdf != null) {
//                        docStructReportPdf.setPdfPath(url.toString());
//                        docStructReportPdf.setUpdateDate(new Date());
//                        docStructReportPdfMapper.updateByPrimaryKeySelective(docStructReportPdf);
//                    } else {
//                        // 插入pdf记录
//                        DocStructReportPdf pdf = new DocStructReportPdf();
//                        Long pdfSoid = soidService.getSoid();
//                        pdf.setStReportPdfSoid(pdfSoid);
//                        pdf.setUpdateUser(employeeSoid);
//                        pdf.setUpdateDate(new Date());
//                        pdf.setStReportLifeCycleSoid(docStructReportLifeCycle.getStReportLifeCycleSoid());
//                        pdf.setCreateDate(new Date());
//                        pdf.setPdfPath(url.toString());
//                        pdf.setIsDelete(0L);
//                        pdf.setStReportSoid(stReportSoid);
//                        docStructReportPdfMapper.insert(pdf);
//                    }
//                }
//            }
//            buildActionSuccess(actionResult);
//        } catch (Exception e) {
//            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//            log.error("保存报告pdf发送异常", e);
//            buildActionWarn(actionResult, "保存报告pdf失败");
//        } finally {
//            // 关闭FTP
//            ftpUtil.closeFTP(ftpClient);
//            stopWatch.stop();
//            log.info("本次保存pdf耗时: " + stopWatch.getTime() + "ms");
//        }
//        return actionResult;
//    }

    @Override
    public ActionResult savePdf(Long stReportSoid, MultipartFile file, Long employeeSoid) {
        log.info("开始保存报告pdf");
        StopWatch stopWatch = StopWatch.createStarted();
        ActionResult actionResult = new ActionResult();
        FTPUtil ftpUtil = new FTPUtil();
        Date date = new Date();
        // 获取FTPClient对象
        FTPClient ftpClient = ftpUtil.getFTPClient(ftpHost, ftpPort, ftpUserName, ftpPassword);

        try {
            if (ObjectUtils.isEmpty(employeeSoid)) {
                buildBadRequestActionWarn(actionResult, "获取不到用户信息");
                return actionResult;
            }

            if (ObjectUtils.isEmpty(stReportSoid)) {
                buildBadRequestActionWarn(actionResult, "报告存储信息标识");
                return actionResult;
            }

            if (file.isEmpty()) {
                buildBadRequestActionWarn(actionResult, "pdf文件不能为空");
                return actionResult;
            }

            DocStructReport docStructReport = docStructReportMapper.selectByPrimaryKey(stReportSoid);
            if (docStructReport != null) {

                // 最新生命周期的id
                Long newestStReportLifeCycleSoid = docStructReport.getStReportLifeCycleSoid();
                // 最新pdf版本号
                Long versionMax = docStructReport.getVersionMax();

                if (ObjectUtils.isNotEmpty(newestStReportLifeCycleSoid)) {
                    DocStructReportLifeCycle LifeCycle = docStructReportLifeCycleMapper.selectByPrimaryKey(newestStReportLifeCycleSoid);
                    if (ObjectUtils.isNotEmpty(LifeCycle)) {
                        // 插入pdf记录
                        DocStructReportPdf pdf = new DocStructReportPdf();
                        Long pdfSoid = soidService.getSoid();
                        pdf.setStReportPdfSoid(pdfSoid);
                        pdf.setUpdateUser(employeeSoid);
                        pdf.setUpdateDate(date);
                        // 关联最新报告生命周期
                        pdf.setStReportLifeCycleSoid(LifeCycle.getStReportLifeCycleSoid());
                        pdf.setCreateDate(date);
                        // 报告pdf url
//                        pdf.setPdfPath(url.toString());
                        pdf.setIsDelete(0L);
                        pdf.setStReportSoid(stReportSoid);
                        docStructReport.setStReportPdfSoid(pdfSoid);
                        if (ObjectUtils.isNotEmpty(versionMax)) {
                            Long newVersion = versionMax + 1;
                            pdf.setVersion(newVersion);
                            // 更新报告主表pdf最新pdf版本号
                            docStructReport.setVersionMax(newVersion);
                            docStructReport.setIsSet(1L);
                        }else {
                            pdf.setVersion(1L);
                            docStructReport.setVersionMax(1L);
                            docStructReport.setIsSet(0L);
                        }

                        // 上传文件到FTP
                        // pdf文件名:患者id + 报告流水号 + 版本号
                        String pdfName = docStructReport.getApntPersonSoid() + "_" + docStructReport.getReportVisitSoid() + "_" + docStructReport.getVersionMax();
                        String savePath = ftpUtil.uploadFile(ftpClient, file, imgPath);
                        StringBuffer stringBuffer = new StringBuffer(nginxUrl);
                        StringBuffer url = stringBuffer.append("/").append(imgPath).append("/").append(savePath);
                        pdf.setPdfPath(url.toString());
                        docStructReportPdfMapper.insert(pdf);
                        srvDocReportService.updateStructReportSelective(docStructReport);
                    }
                }
            }

        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            log.error("保存报告pdf发送异常", e);
            buildActionWarn(actionResult, "保存报告pdf失败");
        } finally {
            // 关闭FTP
            ftpUtil.closeFTP(ftpClient);
            stopWatch.stop();
            log.info("本次保存pdf耗时: " + stopWatch.getTime() + "ms");
        }
        return actionResult;
    }

//    @Override
//    public void getReportPdf(ReportSearchRequest request, HttpServletResponse httpServletResponse) {
//        log.info("开始获取报告pdf");
//        StopWatch stopWatch = StopWatch.createStarted();
//        ListResult listResult = new ListResult();
//        String pdfPath = null;
//        GetMethod getMethod = null;
//        OutputStream outputStream = null;
//
//        try {
//
//            // 根据申请单标识,登记单标识,检查单标识查询
//            DocReportRequisitionRelationVo docReportRequisitionRelationVo = docReportRequisitionRelationMapper.selectAccurateReport(request.getRequestSoid(), request.getRegistrationFormSoid(), request.getExaminationVisitSoid());
//
//            if (ObjectUtils.isNotEmpty(docReportRequisitionRelationVo)) {
//                // 报告存储信息标识
//                Long stReportSoid = docReportRequisitionRelationVo.getStReportSoid();
//                if (ObjectUtils.isNotEmpty(stReportSoid)) {
//                    DocStructReportLifeCycle docStructReportLifeCycle = docStructReportLifeCycleMapper.selectNewestByStReportSoid(stReportSoid);
//                    if (docStructReportLifeCycle != null) {
//                        DocStructReportPdf pdf = docStructReportPdfMapper.selectByLifeCycleSoid(docStructReportLifeCycle.getStReportLifeCycleSoid());
//                        if (pdf != null) {
//                            pdfPath = pdf.getPdfPath();
//                        }
//                    }
//
////                    DocStructReportPdf docStructReportPdf = docStructReportPdfMapper.selectNewestByStReportSoid(stReportSoid);
////                    if (docStructReportPdf != null) {
////                        pdfPath = docStructReportPdf.getPdfPath();
////                    }
//                }
//            }
//
//            if (StringUtils.isNotEmpty(pdfPath)) {
//                outputStream = httpServletResponse.getOutputStream();
//                httpServletResponse.setContentType("application/pdf;charset=UTF-8");
//                httpServletResponse.addHeader("Content-Disposition", "inline;filename=");
//                HttpClient httpClient = new HttpClient();
//                getMethod = new GetMethod(pdfPath);
//                httpClient.executeMethod(getMethod);
//                byte[] response = getMethod.getResponseBody();
//                outputStream.write(response);
//            }
//        } catch (Exception e) {
//            log.error("本次获取报告pdf发送异常", e);
//        } finally {
//            if (getMethod != null) {
//                getMethod.releaseConnection();
//            }
//            try {
//                stopWatch.stop();
//                log.info("本次获取报告pdf耗时: " + stopWatch.getTime() + "ms");
//                if (outputStream != null) {
//                    outputStream.close();
//                }
//            } catch (IOException e) {
//                log.error("pdf文件流关闭失败");
//            }
//        }
//    }

    @Override
    public void getReportPdf(ReportSearchRequest request, HttpServletResponse httpServletResponse) {
        log.info("开始获取报告pdf");
        StopWatch stopWatch = StopWatch.createStarted();
        ListResult listResult = new ListResult();
        String pdfPath = null;
        GetMethod getMethod = null;
        OutputStream outputStream = null;

        try {

            // 根据申请单标识,登记单标识,检查单标识查询
//            DocReportRequisitionRelationVo docReportRequisitionRelationVo = docReportRequisitionRelationMapper.selectAccurateReport(request.getRequestSoid(), request.getRegistrationFormSoid(), request.getExaminationVisitSoid());

//            if (ObjectUtils.isNotEmpty(docReportRequisitionRelationVo)) {
//                // 报告存储信息标识
//                Long stReportSoid = docReportRequisitionRelationVo.getStReportSoid();
//                if (ObjectUtils.isNotEmpty(stReportSoid)) {
//
//                    DocStructReport docStructReport = docStructReportMapper.selectByPrimaryKey(stReportSoid);
//                    Long stReportPdfSoid = docStructReport.getStReportPdfSoid();
//                    if(ObjectUtils.isNotEmpty(stReportPdfSoid)){
//                        DocStructReportPdf pdf = docStructReportPdfMapper.selectByLifeCycleSoid(stReportPdfSoid);
//                        if (pdf != null) {
//                            pdfPath = pdf.getPdfPath();
//                        }
//                    }
//                }
//            }
            Long stReportSoid = request.getStReportSoid();
            if (ObjectUtils.isNotEmpty(stReportSoid)){
                DocStructReport docStructReport = docStructReportMapper.selectByPrimaryKey(stReportSoid);
                if(ObjectUtils.isNotEmpty(docStructReport.getStReportPdfSoid())){
                    DocStructReportPdf pdf = docStructReportPdfMapper.selectByPrimaryKey(docStructReport.getStReportPdfSoid());
                    if (ObjectUtils.isNotEmpty(pdf)){
                        pdfPath = pdf.getPdfPath();
                    }
                }
            }

            if (StringUtils.isNotEmpty(pdfPath)) {
                outputStream = httpServletResponse.getOutputStream();
                httpServletResponse.setContentType("application/pdf;charset=UTF-8");
                httpServletResponse.addHeader("Content-Disposition", "inline;filename=");
                HttpClient httpClient = new HttpClient();
                getMethod = new GetMethod(pdfPath);
                httpClient.executeMethod(getMethod);
                byte[] response = getMethod.getResponseBody();
                outputStream.write(response);
            }
        } catch (Exception e) {
            log.error("本次获取报告pdf发送异常", e);
        } finally {
            if (getMethod != null) {
                getMethod.releaseConnection();
            }
            try {
                stopWatch.stop();
                log.info("本次获取报告pdf耗时: " + stopWatch.getTime() + "ms");
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                log.error("pdf文件流关闭失败");
            }
        }
    }


    @Override
    public List<String> getReportPdfImage() {
        List<String> stringList = new ArrayList<>();
        stringList.add("http://192.168.140.58:8089/image/ultrasoundPicture/lADPD2eDQKedeHjNAVTNAcY_454_340.jpg");
        stringList.add("http://192.168.140.58:8089/image/ultrasoundPicture/lADPD2eDQKedkC_NAyrNBDg_1080_810.jpg");
        stringList.add("http://192.168.140.58:8089/image/ultrasoundPicture/lADPD3lGud9-EC7NASTNAZA_400_292.jpg");
        stringList.add("http://192.168.140.58:8089/image/ultrasoundPicture/lADPD3W5Ozq3eHnNAgjNArs_699_520.jpg");
        stringList.add("http://192.168.140.58:8089/image/ultrasoundPicture/lADPD4BhtykJcpHNAcLNAlg_600_450.jpg");
        stringList.add("http://192.168.140.58:8089/image/ultrasoundPicture/lADPD4d8tHKYECzNAVfNAc8_463_343.jpg");
        stringList.add("http://192.168.140.58:8089/image/ultrasoundPicture/lADPD26ePfEo8pLNATzNAao_426_316.jpg");
//        stringList.add("http://192.168.140.58:8089/image/ultrasoundPicture/1.2.826.0.1.3680043.8.920.34.20210628200239.1.10.dcm");
//        stringList.add("http://192.168.140.58:8089/image/ultrasoundPicture/1.2.826.0.1.3680043.8.920.34.20210628200239.1.2.dcm");
//        stringList.add("http://192.168.140.58:8089/image/ultrasoundPicture/1.2.826.0.1.3680043.8.920.34.20210628200239.1.3.dcm");
//        stringList.add("http://192.168.140.58:8089/image/ultrasoundPicture/1.2.826.0.1.3680043.8.920.34.20210628200239.1.4.dcm");
//        stringList.add("http://192.168.140.58:8089/image/ultrasoundPicture/1.2.826.0.1.3680043.8.920.34.20210628200239.1.5.dcm");
//        stringList.add("http://192.168.140.58:8089/image/ultrasoundPicture/1.2.826.0.1.3680043.8.920.34.20210628200239.1.6.dcm");
//        stringList.add("http://192.168.140.58:8089/image/ultrasoundPicture/1.2.826.0.1.3680043.8.920.34.20210628200239.1.7.dcm");
//        stringList.add("http://192.168.140.58:8089/image/ultrasoundPicture/1.2.826.0.1.3680043.8.920.34.20210628200239.1.8.dcm");
//        stringList.add("http://192.168.140.58:8089/image/ultrasoundPicture/1.2.826.0.1.3680043.8.920.34.20210628200239.1.9.dcm");
        stringList.add("http://192.168.140.58:8089/image/ultrasoundPicture/2700165752572_1_1.jpg");
        stringList.add("http://192.168.140.58:8089/image/ultrasoundPicture/2701153451214_1_1.jpg");
        stringList.add("http://192.168.140.58:8089/image/ultrasoundPicture/2701153451214_1_2.jpg");
        stringList.add("http://192.168.140.58:8089/image/ultrasoundPicture/2701153451214_1_3.jpg");
        stringList.add("http://192.168.140.58:8089/image/ultrasoundPicture/2701153451214_1_4.jpg");
        stringList.add("http://192.168.140.58:8089/image/ultrasoundPicture/2701153451214_1_5.jpg");
        stringList.add("http://192.168.140.58:8089/image/ultrasoundPicture/2701153451214_1_6.jpg");
        stringList.add("http://192.168.140.58:8089/image/ultrasoundPicture/2701153451214_1_7.jpg");
        stringList.add("http://192.168.140.58:8089/image/ultrasoundPicture/2701153451214_1_8.jpg");
        stringList.add("http://192.168.140.58:8089/image/ultrasoundPicture/2701153451214_1_9.jpg");
        return stringList;
    }

    @Override
    public ListResult<String> getReportPdfUrl(ReportSearchRequest request) {
        log.info("开始获取报告pdf");
        ListResult listResult = new ListResult();
        String pdfPath = null;

        if (ObjectUtils.isEmpty(request.getRequestSoid())) {
            buildBadRequestListWarn(listResult, "申请单标识不能为空");
            return listResult;
        }

        // TODO 后面要加上限制
//        if (ObjectUtils.isEmpty(request.getExaminationVisitSoid())) {
//            buildBadRequestListWarn(listResult, "检查标识不能为空");
//            return listResult;
//        }

        try {

            // 申请单与检查实例关系信息
//            List<DocReportRequisitionRelationVo> docReportRequisitionRelationVoList = docReportRequisitionRelationMapper.selectByRequestSoid(requestSoid);

            DocReportRequisitionRelationVo docReportRequisitionRelationVo = docReportRequisitionRelationMapper.selectAccurateReport(request.getRequestSoid(), request.getRegistrationFormSoid(), request.getExaminationVisitSoid());

            if (ObjectUtils.isNotEmpty(docReportRequisitionRelationVo)) {
                // 报告存储信息标识
                Long stReportSoid = docReportRequisitionRelationVo.getStReportSoid();
                if (ObjectUtils.isNotEmpty(stReportSoid)) {
                    DocStructReportPdf docStructReportPdf = docStructReportPdfMapper.selectNewestByStReportSoid(stReportSoid);
                    if (docStructReportPdf != null) {
                        pdfPath = docStructReportPdf.getPdfPath();
                    }
                }
            }
            buildListSuccess(listResult, pdfPath);

        } catch (Exception e) {
            log.error("本次获取报告pdf发送异常", e);
        }
        return listResult;
    }

    public ListResult<Map<String, List<String>>> getReportPdfHistory(List<Long> requestSoidList) {
        log.info("开始获取报告历史pdf");
        ListResult<Map<String, List<String>>> listResult = new ListResult();
        Map<String, List<String>> history = new HashMap<>();
        try {
            if (CollectionUtils.isEmpty(requestSoidList)) {
                buildBadRequestListWarn(listResult, "申请单标识list不能为空");
                return listResult;
            }
            for (Long requestSoid : requestSoidList) {
                List<String> list = new ArrayList<>();
                List<Long> stReportSoidlist = docReportRequisitionRelationMapper.selecStReportSoidByRequestSoid(requestSoid);
                if (CollectionUtils.isNotEmpty(stReportSoidlist)) {
                    for (Long stReportSoid : stReportSoidlist) {
                        DocStructReportLifeCycle docStructReportLifeCycle = docStructReportLifeCycleMapper.selectNewestByStReportSoid(stReportSoid);
                        if (ObjectUtils.isNotEmpty(docStructReportLifeCycle)) {
                            DocStructReportPdf pdf = docStructReportPdfMapper.selectByLifeCycleSoid(docStructReportLifeCycle.getStReportLifeCycleSoid());
                            if (ObjectUtils.isNotEmpty(pdf)) {
                                list.add(pdf.getPdfPath());
                            }
                        }
                    }
                }
                history.put(requestSoid.toString(), list);
            }

            buildListSuccess(listResult, history);
        } catch (Exception e) {
            log.error("本次获取报告历史pdf发送异常", e);
        }
        return listResult;
    }

    /**
     * 根据报告标识获取对应相关PDF报告路径
     * @param request
     * @return
     * @throws Exception
     */
    @Override
    public String gainReportPdfByStReportSoid(ReportSearchRequest request) throws Exception {
        log.info("开始根据报告标识获取对应相关PDF报告路径");
        StopWatch stopWatch = StopWatch.createStarted();
        String pdfUrl = CharacterConst.SpecialSymbol.EMPTY;
        pdfUrl = docStructReportMapper.gainReportPdfByStReportSoid(request);
        stopWatch.stop();
        log.info("本次获取报告pdf耗时: " + stopWatch.getTime() + "ms");
        return pdfUrl;
    }
}
